package com.limao.CacheManager;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.limao.DBDataClass.CrowdUserAuthClass;
import com.limao.DBDataClass.MobileCodeDataClass;
import com.limao.DBDataClass.UserOffLineDataClass;
import com.limao.DBProvider.UserOfflineProvider;
import com.limao.DBProvider.UserRmbProvider;
import com.limao.Model.LzPluginException;
import com.limao.Model.PublicData;
import com.limao.Model.RecvData;
import com.limao.Tool.CacheClass;
import com.limao.Tool.SMSUtil;
import com.limao.Utils.OutPrintClass;


public class RegLoginInfo {

	//新鲜宝 登陆
	public static Object login(HttpSession session,String selfSessionId,HttpServletResponse response,AsyncContext asyncContext,int m,RecvData DataObj) throws LzPluginException
	{

		if (CacheClass.isEmpty(DataObj.mobile) || CacheClass.isEmpty(DataObj.password)) {
			throw new LzPluginException("用户名与密码不能为空");
		} 

        if(CacheClass.isEmpty(DataObj.platform)){
    		throw new LzPluginException("登录参数传递有误");
    	}
       
		CrowdUserAuthClass tmp=CrowdUserAuthCache.getInstance().AuthLogin(DataObj.mobile, DataObj.password.toUpperCase(), DataObj.platform, DataObj.token, DataObj.cid);
	
		//登陆交易所
/*		
		if(tmp!=null)
		{
			Map<String, String> sParaTemp=new HashMap<String, String>();
			sParaTemp.put("c", "5");
			sParaTemp.put("account", "13798485970");
			sParaTemp.put("pwd", "123456");
			ResultModel result=null;
			try {
				result=Api.buildRequest(sParaTemp);
			} catch (Exception e) {
				result=null;
				e.printStackTrace();
			}
			if(result==null || CacheClass.getIntValue(result.retcode)!=0)
			{
				System.out.println("登陆交易所");
				throw new LzPluginException( "出错,登陆失败,retcode="+result.retcode+":"+result.GetRetMsg());
			}
			//保存cookie内的用户标识到CACHE
		
		}
*/
		
		//登陆成功
		CacheClass.Login(session,selfSessionId,tmp);
	
		PublicData data =new PublicData();
		data.m =m+"";
		data.state = "1";
		data.userid = tmp.userid;
		data.token=selfSessionId;
		data.info = "登陆成功  ";
		data.obj=tmp.obj;
		return data;


	}
	
	
	//新鲜宝 安全退出登陆
	public static Object loginout(HttpSession session,String selfSessionId,HttpServletResponse response,AsyncContext asyncContext,int m,RecvData DataObj) throws LzPluginException
	{
		DataObj.userid=SessionCacheManager.getInstance().GetSessionCache(selfSessionId);
		if(!CacheClass.isEmpty(DataObj.userid))
		{
			//更新上线纪录 
			UserOffLineDataClass tmp=UserOfflineProvider.getInstance().updateUserOffline(CacheClass.getIntValue(DataObj.userid),CacheClass.getIntValue(DataObj.platform), 0,DataObj.token);
			if(tmp==null)//退出登陆
			{
				throw new LzPluginException("退出登陆,出错");
			}
		}
		
		//退出登陆成功
		
		CacheClass.outLogin(session,selfSessionId);
		
		return OutPrintClass.resultObj(m,"退出登陆成功  ");
		
	}
	
	public static String md5(String inputStr) throws NoSuchAlgorithmException {
	    String md5Str = inputStr;
	    if(inputStr != null) {
	        MessageDigest md = MessageDigest.getInstance("MD5");
	        try {
				md.update(inputStr.getBytes("UTF-8"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        BigInteger hash = new BigInteger(1, md.digest());
	        md5Str = hash.toString(16);
	        if((md5Str.length() % 2) != 0) {
	            md5Str = "0" + md5Str;
	        }
	    }
	    return md5Str;
	}
	
	//用户名注册
	public static Object getCode(HttpSession session,HttpServletResponse response,AsyncContext asyncContext,int m,RecvData DataObj) throws LzPluginException
	{

		String mobile = DataObj.mobile.trim();
		if (CacheClass.isEmpty(mobile)) {
			throw new LzPluginException("出错,参数不能为空");
		}
		
		String imgcode=DataObj.imgcode;
		String sessionCode = (String) session.getAttribute("code");
		if(!CacheClass.isEmpty(sessionCode))
		{
			if (CacheClass.isEmpty(imgcode)) {
				throw new LzPluginException("出错,图形码不能为空");
			}
			if(!sessionCode.equalsIgnoreCase(imgcode))
			{
				System.out.println("图形码="+sessionCode+",用户输码="+imgcode);
				throw new LzPluginException("出错,图形码不正确");
			}
		}

		if (!CacheClass.isMobileNO(mobile)) {
			throw new LzPluginException("出错,手机号格式不正确");
		}
		
		// 是否已注册或被绑定
		if (CrowdUserAuthCache.getInstance().isHave(mobile)) {
			throw new LzPluginException("出错,该手机已注册或绑定");
		}

		return getCode(m, mobile);
		
		
	}	

	public static Object getCode(int m, String mobile) throws LzPluginException 
	{
		String strCode = null;

		MobileCodeDataClass codeTmp = CacheClass.getMobileCodeCacheManger().loadMobileCode(mobile);
		if (codeTmp != null && !CacheClass.isEmpty(codeTmp.code_code)) {
			strCode = codeTmp.code_code;
			long loadcodetime = CacheClass.getLongValue(codeTmp.loadcodetime);
			long current = CacheClass.getTime();

			if ((current - loadcodetime) < (1 * 60 * 1000)) // 距离上次获取验证码少于1分钟
			{
				throw new LzPluginException("请求验证码必须间隔60秒");
			}else if((current - loadcodetime) > (5 * 60 * 1000)){
				// 距离上次获取验证码超过3分钟
				// 重新生成code
				strCode = CacheClass.get6RandomCode();
			}
			if(CacheClass.getIntValue(codeTmp.sendnum) > 2){
				throw new LzPluginException("短信验证码已发送3次, 30分钟后再请求");
			}
			
			// 更新本次取验证码时间
			CacheClass.getMobileCodeCacheManger().updateCodeTime(mobile, strCode, current);
			
		} else {
			strCode = CacheClass.get6RandomCode();
			MobileCodeDataClass tmp = CacheClass.getMobileCodeCacheManger()
												.createCode(mobile, strCode);
			if (tmp == null) {
				throw new LzPluginException("服务器建立验证码出错");
			}

		}

		// 发短信(测试时发推送)
		boolean success = SMSUtil.sendSMS(mobile, strCode);
		
		if (success){
			if(CacheClass.ISDEBUG==1){
				throw new LzPluginException("验证码已发送,请注意收查短信,验证码:" + strCode);
			}else{
				return OutPrintClass.resultObj(m,"验证码已发送,请注意收查短信");
			}
		}else{
			throw new LzPluginException("验证码发送失败");
		}

		 
	}
	
	
	public static Object codeAuth(HttpServletResponse response,AsyncContext asyncContext,int m,RecvData DataObj) throws LzPluginException
	{
		
		if (CacheClass.isEmpty(DataObj.mobile)
				|| CacheClass.isEmpty(DataObj.code)) {
			throw new LzPluginException( "验证码或手机号为空");
		}

		MobileCodeDataClass codeTmp = CacheClass.getMobileCodeCacheManger().loadMobileCode(DataObj.mobile);
		if (codeTmp == null || CacheClass.isEmpty(codeTmp.code_code)) {
			throw new LzPluginException( "验证码不存在或已过期");
		}
		if (!CacheClass.myEqualsIgnoreCase(DataObj.code, codeTmp.code_code)) {
			throw new LzPluginException( "验证码不正确");
		}
		
		// 验证码正确
		return OutPrintClass.resultObj(m, "验证码正确");
	}
	
	
	public static Object AuthInfo(HttpServletResponse response,AsyncContext asyncContext,int m,RecvData DataObj) throws LzPluginException
	{
		if (CacheClass.isEmpty(DataObj.mobile)
				|| CacheClass.isEmpty(DataObj.code)
				|| CacheClass.isEmpty(DataObj.password)
				|| CacheClass.isEmpty(DataObj.codepassword) )
		{
			throw new LzPluginException( "出错，数据项不能为空");
		}
		//推荐人是否正确
		if(!CacheClass.isEmpty(DataObj.introduceId) ){
			if( !CacheClass.isIntegerNumber2(DataObj.introduceId))
			{
				throw new LzPluginException( "出错，推荐人格式不正确");
			}
			
			int introduceId=CacheClass.getIntValue(DataObj.introduceId);
			if(introduceId<500)// 少于500认定为分公司id
			{
				String smallcompanyid = UserRmbProvider.getInstance().load_Small_comapny(introduceId);
				if(smallcompanyid == null){
					throw new LzPluginException( "出错，分公司不存在");
				}
			}
			else
			{
				CrowdUserAuthClass userAuth = CrowdUserAuthCache.getInstance().getUser(CacheClass.getIntValue(DataObj.introduceId));
				if(userAuth == null){
					throw new LzPluginException( "出错，推荐人不存在");
				}
			}
		}
		

		MobileCodeDataClass codeTmp = CacheClass.getMobileCodeCacheManger()
				.loadMobileCode(DataObj.mobile);
		if (codeTmp == null || CacheClass.isEmpty(codeTmp.code_code)) {
			return OutPrintClass.errorObj(m, "验证码不存在或已过期");
			
		}
		if (!CacheClass.myEqualsIgnoreCase(codeTmp.code_code, DataObj.code)) {
			return OutPrintClass.errorObj(m, "验证码不正确");
			
		}
		codeTmp = null;
		
		// 是否已注册或被绑定
		if (CrowdUserAuthCache.getInstance().isHave(DataObj.mobile)) {
			throw new LzPluginException( "出错,该手机已注册或绑定");
		}

		System.out.println("注册-开始");
		CrowdUserAuthClass tmp=CrowdUserAuthCache.getInstance().createUsernmae(DataObj.mobile, DataObj.password.toUpperCase(), DataObj.introduceId,DataObj.codepassword.trim());
		
		
		if (tmp!= null) {
			return OutPrintClass.resultObj(m, "注册成功");
		} else {
			throw new LzPluginException( "出错,注册失败");
		}
		
	}
	
	
	
	public static Object getCode2(HttpServletResponse response,AsyncContext asyncContext,int m,RecvData DataObj) throws LzPluginException
	{
		
		String mobile = DataObj.mobile.trim();
		if (CacheClass.isEmpty(mobile)) {
			throw new LzPluginException( "出错,参数不能为空");
		}

		if (!CacheClass.isMobileNO(mobile)) {
			throw new LzPluginException( "出错,手机号格式不正确");
		}

		// 是否已绑定
		boolean flag=CrowdUserAuthCache.getInstance().isHave(DataObj.mobile);
		if(flag )
		{
				return getCode(m, mobile);
		}
		else
		{
				throw new LzPluginException( "出错,该手机未绑定");
		}

	}
	
	
	public static Object setNewMobile(HttpServletResponse response,AsyncContext asyncContext,int m,RecvData DataObj) throws LzPluginException
	{
		
		if (CacheClass.isEmpty(DataObj.oldmobile) || CacheClass.isEmpty(DataObj.newmobile) || CacheClass.isEmpty(DataObj.code)) 
		{
			throw new LzPluginException( "验证码或绑定号为空");
		}

		if (!CacheClass.isMobileNO(DataObj.newmobile) || !CacheClass.isMobileNO(DataObj.oldmobile)) {
			throw new LzPluginException( "出错,手机号格式不正确");
		}

		MobileCodeDataClass codeTmp = CacheClass.getMobileCodeCacheManger().loadMobileCode(DataObj.oldmobile);
		if (codeTmp == null) 
		{
			throw new LzPluginException( "验证码过期,请重新获取");
		}
		if (!CacheClass.myEqualsIgnoreCase(DataObj.code, codeTmp.code_code)) {
			return OutPrintClass.errorObj(m, "验证码不正确");
			
		}
		codeTmp = null;

		 //参数检查2（非空检查）

		// 验证码正确

		// 新手机号是否已被注册
		// 是否已注册或被绑定
		if (CrowdUserAuthCache.getInstance().isHave(DataObj.newmobile)) {
			throw new LzPluginException( "出错,该手机已注册或绑定");
		}
		
		
		CrowdUserAuthClass tmpAuth=CrowdUserAuthCache.getInstance().getUserBymobile(DataObj.oldmobile);
		if(tmpAuth == null)
		{
			return  OutPrintClass.errorObj(m, "无此用户");
			
		}

		
			
		tmpAuth = CrowdUserAuthCache.getInstance().UPDATA_User_auth_mobile(DataObj.newmobile,CacheClass.getIntValue(tmpAuth.userid));
		if (tmpAuth == null) {
			throw new LzPluginException( "修改绑定号失败");
		}
		

		CacheClass.getMobileCodeCacheManger().deleteMobileCode(DataObj.oldmobile);
		
		return OutPrintClass.resultObj(m, "修改绑定号成功");
		
		
	}
	
	public static Object setNewPassword(HttpServletResponse response,AsyncContext asyncContext,int m,RecvData DataObj) throws LzPluginException
	{
		
		if (CacheClass.isEmpty(DataObj.mobile)
				|| CacheClass.isEmpty(DataObj.password)
				|| CacheClass.isEmpty(DataObj.code)
				|| CacheClass.isEmpty(DataObj.codepassword)	) 
		{
			throw new LzPluginException( "验证码或绑定号或密码为空");
		}

		MobileCodeDataClass codeTmp = CacheClass.getMobileCodeCacheManger().loadMobileCode(DataObj.mobile);
		if (codeTmp == null) 
		{
			throw new LzPluginException( "验证码过期,请重新获取");
		}
		if (!CacheClass.myEqualsIgnoreCase(DataObj.code, codeTmp.code_code))
		{
			throw new LzPluginException( "验证码不正确");
		}
		codeTmp = null;
		// 验证码正确
		CrowdUserAuthClass tmpAuth = CrowdUserAuthCache.getInstance()
				.UPDATA_User_auth_password_ByMobile(DataObj.mobile,
						DataObj.password.toUpperCase(),DataObj.codepassword.trim());
		if (tmpAuth != null) {
			CacheClass.getMobileCodeCacheManger().deleteMobileCode(DataObj.mobile);
			return OutPrintClass.resultObj(m, "修改密码成功");
		} else {
			throw new LzPluginException( "修改密码失败");
		}
		
		
	}
	
	
	public static Object setNewPassword_afterLogin(HttpServletResponse response,AsyncContext asyncContext,int m,RecvData DataObj) throws LzPluginException
	{
		
		if (CacheClass.isEmpty(DataObj.userid)
				|| CacheClass.isEmpty(DataObj.password)
				|| CacheClass.isEmpty(DataObj.oldpassword)
				|| CacheClass.isEmpty(DataObj.codepassword)	) 
		{
			return OutPrintClass.errorObj(m, "用户信息或密码为空");
			
		}
		if (CacheClass.isEmpty(DataObj.oldpassword.toUpperCase())) {
			return OutPrintClass.errorObj(m, "旧密码为空");
			
		}
		if (DataObj.password.toUpperCase().equals(DataObj.oldpassword.toUpperCase())) {
			throw new LzPluginException("新旧密码不能相同");
		}

		// 验证码正确
		CrowdUserAuthClass tmpAuth = CrowdUserAuthCache.getInstance().UPDATA_User_auth_password_ById(
						CacheClass.getIntValue(DataObj.userid), DataObj.password.toUpperCase(),
						DataObj.oldpassword.toUpperCase(),DataObj.codepassword.trim());
		if (tmpAuth != null) {
			return OutPrintClass.resultObj(m, "修改密码成功");
		} else {
			throw new LzPluginException( "修改密码失败");
		}
		
		
	}
	
	
	//测试用注册
	public static Object AuthInfo_ForTest(HttpServletResponse response,AsyncContext asyncContext,int m,RecvData DataObj) throws LzPluginException
	{
		if (CacheClass.isEmpty(DataObj.mobile)
				|| CacheClass.isEmpty(DataObj.password)) 
		{
			throw new LzPluginException( "出错，数据项不能为空");
		}
		//推荐人是否正确
		if(!CacheClass.isEmpty(DataObj.introduceId) ){
			if( !CacheClass.isIntegerNumber2(DataObj.introduceId))
			{
				throw new LzPluginException( "出错，推荐人格式不正确");
			}
			CrowdUserAuthClass userAuth = CrowdUserAuthCache.getInstance().getUser(CacheClass.getIntValue(DataObj.introduceId));
			if(userAuth == null){
				throw new LzPluginException( "出错，推荐人不存在");
			}
		}
		

		
		// 是否已注册或被绑定
		if (CrowdUserAuthCache.getInstance().isHave(DataObj.mobile)) {
			throw new LzPluginException( "出错,该手机已注册或绑定");
		}

		System.out.println("注册-开始");
		CrowdUserAuthClass tmp=CrowdUserAuthCache.getInstance().createUsernmae(DataObj.mobile, DataObj.password.toUpperCase(), DataObj.introduceId,"");
		
		
		if (tmp!= null) {
			return OutPrintClass.resultObj(m, "注册成功");
		} else {
			throw new LzPluginException( "出错,注册失败");
		}
		
	}
	
	
	//新鲜宝 登陆
		public static Object login_ForTest(HttpSession session,String selfSessionId,HttpServletResponse response,AsyncContext asyncContext,int m,RecvData DataObj) throws LzPluginException
		{

			if (CacheClass.isEmpty(DataObj.mobile) || CacheClass.isEmpty(DataObj.password)) {
				throw new LzPluginException("用户名与密码不能为空");
			} 

	        if(CacheClass.isEmpty(DataObj.platform)){
	    		throw new LzPluginException("登录参数传递有误");
	    	}
	       
			CrowdUserAuthClass tmp=CrowdUserAuthCache.getInstance().AuthLogin(DataObj.mobile, DataObj.password.toUpperCase(), DataObj.platform, DataObj.token, DataObj.cid);
		
			//登陆交易所
	/*		
			if(tmp!=null)
			{
				Map<String, String> sParaTemp=new HashMap<String, String>();
				sParaTemp.put("c", "5");
				sParaTemp.put("account", "13798485970");
				sParaTemp.put("pwd", "123456");
				ResultModel result=null;
				try {
					result=Api.buildRequest(sParaTemp);
				} catch (Exception e) {
					result=null;
					e.printStackTrace();
				}
				if(result==null || CacheClass.getIntValue(result.retcode)!=0)
				{
					System.out.println("登陆交易所");
					throw new LzPluginException( "出错,登陆失败,retcode="+result.retcode+":"+result.GetRetMsg());
				}
				//保存cookie内的用户标识到CACHE
			
			}
	*/
			
			//登陆成功
			CacheClass.Login(session,selfSessionId,tmp);
		
			PublicData data =new PublicData();
			data.m =m+"";
			data.state = "1";
			data.userid = tmp.userid;
			data.account = tmp.mobile;
			data.pwd = tmp.pwd;
			data.token=selfSessionId;
			data.info = "登陆成功  ";
			data.obj=tmp.obj;
			return data;


		}
}
